package com.sbck.cs3.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.sbck.cs3.MyClass.FileUtils;
import com.sbck.cs3.MyGlobal;
import com.sbck.cs3.R;
import com.sbck.cs3.databinding.FragmentLoginBinding;

public class LoginFragment extends Fragment {

    FragmentLoginBinding mBinding;

    DeviceSelectFragment deviceSelectFragment;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);

        deviceSelectFragment = new DeviceSelectFragment();

        FileUtils.ReadLoginInfo();

        mBinding = FragmentLoginBinding.inflate(inflater,container,false);
        mBinding.setUser(MyGlobal.loginUser);

        return mBinding.getRoot();
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Button button = view.findViewById(R.id.Btn_Login);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(MyGlobal.loginUser.LoginName.get() == null )
                {
                    Toast.makeText(getActivity(),"请输入你的DTU编号",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(MyGlobal.loginUser.Password.get() == null )
                {
                    Toast.makeText(getActivity(),"请输入密码",Toast.LENGTH_SHORT).show();
                    return;
                }
                try
                {
                    if(!MyGlobal.loginUser.LoginName.get().equals("sbck"))
                    {
                        Integer.parseInt(MyGlobal.loginUser.LoginName.get());
                    }
                }
                catch (Exception ee)
                {
                    Toast.makeText(getActivity(),"DTU编号必须是4开头的9位数字",Toast.LENGTH_SHORT).show();
                    return;
                }

                if(!MyGlobal.loginUser.LoginName.get().equals(MyGlobal.loginUser.Password.get().toString()))
                {
                    Toast.makeText(getActivity(),"输入的DTU编号或密码不对",Toast.LENGTH_SHORT).show();
                    return;
                }
                FileUtils.SaveLoginInfo();


                getFragmentManager().beginTransaction().replace(R.id.fl_DeviceSelect_container,deviceSelectFragment).commitNowAllowingStateLoss();
            }
        });
    }
}